package com.yf.dxs.wo.service.impl;

import com.alibaba.fastjson2.JSON;
import com.yf.dxs.wo.dao.WoOrderMsgMapper;
import com.yf.dxs.wo.entity.WoOrderMsgDO;
import com.yf.dxs.wo.redis.RedisMqTemplate;
import com.yf.dxs.wo.req.msg.WoOrderMsg;
import com.yf.dxs.wo.service.MsgHandler;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * 订单状态变更
 * https://doc.weimobcloud.com/search?key=weimob_shop.order/statusUpdate
 */

@Service
@Slf4j
public class OrderHandler implements MsgHandler {

    @Resource
    private WoOrderMsgMapper orderMapper;

    @Resource
    public RedisMqTemplate redisMqTemplate;

    public void handle(String msgId, String msgBody, String event) {
        WoOrderMsg orderMsg = JSON.parseObject(msgBody, WoOrderMsg.class);
        WoOrderMsgDO woOrder = orderMsg.toEntity();
        woOrder.setMsgId(msgId);
        if(orderMsg.getPaymentStatus()!=2){ //不是支付状态直接返回
            return;
        }
        // 不是已支付 确认收货 完成(退款也触发完成) 9是取消 但是只有未支付可以取消
        if(!Arrays.asList(2,7,8).contains(orderMsg.getOrderStatus())){
            return;
        }
        log.info("处理订单:{},{},{},{},{},{}", event, woOrder.getOrderNo(), woOrder.getWid(), woOrder.getOrderStatus(), woOrder.getPaymentStatus(), woOrder.getUpdateTime());
        int i = orderMapper.insert(woOrder);
        if (i == 0) {
            log.error("插入失败..{},{}", orderMsg.getOrderNo(), orderMsg.getWid());
        } else {
            log.info("插入成功..{},{}", orderMsg.getOrderNo(), orderMsg.getWid());
            redisMqTemplate.sendMsg(woOrder);
        }
    }
}
